#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QDebug>
#include<QFileDialog>
#include<fstream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //一个mainwindow一般包括：菜单栏（menu bar，唯一）、多个⼯具栏(tool bars)、
    //多个浮动窗⼝（铆接部件）(dock widgets)、⼀个状态栏(status bar) 和⼀个 中⼼部件(central widget)
    this->setWindowTitle("我的记事本");

    QMenuBar* menubar=new QMenuBar(this);
    this->setMenuBar(menubar);

    //菜单栏
    QMenu* menufile=new QMenu("文件");
    menubar->addMenu(menufile);

    //菜单
    QAction* save=new QAction("保存");
    QAction* load=new QAction("加载");

    menufile->addAction(save);
    menufile->addAction(load);

    //添加主控件，如TextEdit方便查看文本
    textedit=new QTextEdit(this);//写不写this都行，已经是widget的成员了
    this->setCentralWidget(textedit);//设为主控件
    textedit->setPlaceholderText("此处编写⽂本内容...");

    //连接信号
    connect(save, &QAction::triggered, this, &MainWindow::save);
    connect(load, &QAction::triggered, this, &MainWindow::load);


}

void MainWindow::save()
{
    // 弹出对话框, 选择写⼊⽂件的路径
    QFileDialog* dialog = new QFileDialog(this);
    QString fileName = dialog->getSaveFileName(this, "保存⽂件", "D:/code/qt");
    qDebug() << "fileName: " << fileName;
    // 写⼊⽂件
    std::ofstream file(fileName.toStdString().c_str());
    if (!file.is_open()) {
        qDebug() << "⽂件保存失败!";
        return;
    }
    const QString& text = textedit->toPlainText();
    file << text.toStdString();
    file.close();
}
void MainWindow::load()
{
    // 弹出对话框, 选择打开的⽂件
    QFileDialog* dialog = new QFileDialog(this);
    QString fileName = dialog->getOpenFileName(this, "加载⽂件", "D:/code/qt");//初始查找路径
    qDebug() << "fileName: " << fileName;
    // 读取⽂件
    std::ifstream file(fileName.toStdString().c_str());
    if (!file.is_open())
    {
        qDebug() << "⽂件加载失败!";
        return;
    }
    std::string content;
    std::string line;
    while (std::getline(file, line))
    {
        content += line;
        content += "\n";
    }
    file.close();
    // 显⽰到界⾯上
    //记得转换格式
    QString text = QString::fromStdString(content);
    textedit->setPlainText(text);
    //hahaha
}

MainWindow::~MainWindow()
{
    delete ui;
}
